import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { StoreService, queryCondition } from './store.service';
import {
  Condition,
  Statistic,
  Aggregation,
  Query,
  QueryPackage,
  ConditionGroup,
  QueryParameter,
  StatisticTerm,
  CalculateTerm,
} from './classes';
import { DomSanitizer } from '@angular/platform-browser';
@Injectable({
  providedIn: 'root',
})
export class DataService {
  constructor(
    private httpService: HttpClient,
    private store: StoreService,
    private sanitizer: DomSanitizer
  ) {}
  public isLogined(): boolean {
    if (!this.store.Authorize) return true;
    if (
      this.store.loginUser === undefined ||
      this.store.loginUser.UserName === undefined ||
      this.store.loginUser.UserName === ''
    )
      return false;
    return true;
  }
  public async getModel(user, id, earliest, queryName, queryAuthor) {
    if (!this.isLogined()) {
      alert('没有操作权限，请联系管理员');
      return;
    }
    console.log('start get model');
    let para = {};
    para['user'] = user;
    para['id'] = id;
    para['limit'] = this.store.maxModel;
    para['moreTime'] = earliest;
    para['queryUsername'] = queryAuthor;
    para['queryName'] = queryName;
    let furl = this.store.conf.apiUrl + 'model';
    furl = furl + '?';

    //params['operatorID'] = 'test';
    for (const key of Object.keys(para)) {
      if (para.hasOwnProperty(key) && para[key] !== undefined) {
        furl = furl + key + '=' + para[key] + '&';
      }
    }
    const header = {
      'Content-Type': 'application/json',
    };
    return await this.httpService
      .get(furl, {
        headers: header,
        responseType: 'json',
      })
      .toPromise()
      .then(
        (data) => {
          // console.log('data:');
          // console.log(data);

          // console.log('data body:');
          // console.log(data['body']);
          return data['body'];
        },
        (error) => {
          console.log(error);
        }
      );
  }
  //#region QueryPackage
  public isQuery(qp: QueryPackage): boolean {
    if (qp.type === undefined) return false;
    if (qp.type === 'query' || qp.type.trim() === 'query') return true;
    return false;
  }
  public isAggregation(qp: QueryPackage): boolean {
    if (qp.type === undefined) return false;
    if (qp.type === 'aggregation' || qp.type.trim() === 'aggregation')
      return true;
    return false;
  }
  public getQueryObject(qp: QueryPackage): any {
    if (qp.query !== undefined && qp.query !== '') {
      if (this.isQuery(qp)) return JSON.parse(qp.query) as Query;
      if (this.isAggregation(qp)) return JSON.parse(qp.query) as Aggregation;
    }
    return undefined;
  }
  public setQueryObject(obj: any, qp: QueryPackage, type: string) {
    // console.log(obj);
    // console.log(typeof obj);
    // console.log(obj instanceof Aggregation);
    if (obj instanceof Query || type === 'query') {
      qp.type = 'query';
      qp.query = JSON.stringify(obj);
    }
    if (obj instanceof Aggregation || type === 'aggregation') {
      qp.type = 'aggregation';
      qp.query = JSON.stringify(obj);
    }
  }
  //#endregion
  public UpdatePublicConditionsForQuery(
    query: Query,
    publicConditionList: Condition[]
  ) {
    let i = 0;
    query.conditionpipe.forEach((l) => {
      let cs: Condition[] = [];
      l.conditions.forEach((c) => {
        if (c.Public) {
          cs.push(publicConditionList[i]);
          i++;
        } else {
          cs.push(c);
        }
      });
      l.conditions = cs;
    });
  }
  public UpdatePublicConditionsForAggregation(
    aggregation: Aggregation,
    publicConditionList: Condition[]
  ) {
    let i = 0;
    aggregation.conditionpipe.forEach((l) => {
      let cs: Condition[] = [];
      l.conditions.forEach((c) => {
        if (c.Public) {
          cs.push(publicConditionList[i]);
          i++;
        } else {
          cs.push(c);
        }
      });
      l.conditions = cs;
    });
  }
  public getPublicCondition(item: QueryPackage) {
    let cl = [];
    if (this.isQuery(item)) {
      let query = this.getQueryObject(item) as Query;
      query.conditionpipe.forEach((l) => {
        l.conditions.forEach((c) => {
          if (c.Public) cl.push(c);
        });
      });

      return cl;
    }
    if (this.isAggregation(item)) {
      let query = this.getQueryObject(item) as Aggregation;
      query.conditionpipe.forEach((l) => {
        l.conditions.forEach((c) => {
          if (c.Public) cl.push(c);
        });
      });
      return cl;
    }
    return cl;
  }
  public getPackageVersion(item: QueryPackage) {
    let cl = [];
    if (this.isQuery(item)) {
      let query = this.getQueryObject(item) as Query;

      return query.version;
    }
    if (this.isAggregation(item)) {
      let query = this.getQueryObject(item) as Aggregation;

      return query.version;
    }
    return '';
  }
  public getValidAggregation(item): [] {
    let info = this.getInfo(item.show);
    let t = 'str';
    if (info.datatype === 'num') t = 'num';
    if (info.datatype === 'date') t = 'date';
    return this.store.validAggregation[t];
  }
  public cloneObject(source) {
    const obj = {};
    if (source === undefined) return obj;
    for (const key in source) {
      if (Object.prototype.hasOwnProperty.call(source, key)) {
        const element = source[key];
        if (element !== undefined && typeof element == 'function')
          obj[key] = element;
        if (
          typeof element == 'number' ||
          typeof element == 'string' ||
          typeof element == 'bigint' ||
          typeof element == 'symbol' ||
          typeof element == 'boolean'
        )
          obj[key] = element;

        if (typeof element == 'object') {
          if (Array.isArray(element)) {
            obj[key] = [];
            for (var i = 0; i < element.length; i++) {
              obj[key].push(this.cloneObject(element[i]));
            }
          } else {
            obj[key] = this.cloneObject(element);
          }
        }
      }
    }
    return obj;
  }

  public cloneQuery(query: Query) {
    const q = new Query();
    if (query.name !== undefined && query.name !== null) q.name = query.name;
    if (query.version !== undefined && query.version !== null)
      q.version = query.version;
    if (query.showColumn !== undefined && query.showColumn !== null)
      query.showColumn.forEach((s) => q.showColumn.push(s));
    q.parameter = new QueryParameter();
    if (
      query.parameter !== undefined &&
      query.parameter.distinctMrid !== undefined &&
      query.parameter.distinctMrid !== null
    )
      q.parameter.distinctMrid = query.parameter.distinctMrid;
    if (
      query.parameter !== undefined &&
      query.parameter.isMridMode !== undefined &&
      query.parameter.isMridMode !== null
    )
      q.parameter.isMridMode = query.parameter.isMridMode;
    if (
      query.parameter !== undefined &&
      query.parameter.limit !== undefined &&
      query.parameter.limit !== null
    )
      q.parameter.limit = query.parameter.limit;
    if (
      query.parameter !== undefined &&
      query.parameter.sequence !== undefined &&
      query.parameter.sequence !== null
    )
      q.parameter.sequence = query.parameter.sequence;
    if (
      query.parameter !== undefined &&
      query.parameter.strict !== undefined &&
      query.parameter.strict !== null
    )
      q.parameter.strict = query.parameter.strict;
    if (query.conditionpipe !== undefined && query.conditionpipe !== null)
      query.conditionpipe.forEach((p) => {
        const group = new ConditionGroup();
        if (p.name !== undefined && p.name !== null) group.name = p.name;
        if (p.relation !== undefined && p.relation !== null)
          group.relation = p.relation;
        if (p.conditions !== undefined && p.conditions !== null)
          p.conditions.forEach((c) => {
            const condition = new Condition();
            if (c.AddtionalValue !== undefined && c.AddtionalValue !== null)
              condition.AddtionalValue = c.AddtionalValue;
            if (c.DataType !== undefined && c.DataType !== null)
              condition.DataType = c.DataType;
            if (c.Db !== undefined && c.Db !== null) condition.Db = c.Db;
            if (c.DicColumns !== undefined && c.DicColumns !== null)
              condition.DicColumns = c.DicColumns;
            if (c.DicTable !== undefined && c.DicTable !== null)
              condition.DicTable = c.DicTable;
            if (c.IsShow !== undefined && c.IsShow !== null)
              condition.IsShow = c.IsShow;
            if (c.Operation !== undefined && c.Operation !== null)
              condition.Operation = c.Operation;
            if (c.Public !== undefined && c.Public !== null)
              condition.Public = c.Public;
            if (c.Relation !== undefined && c.Relation !== null)
              condition.Relation = c.Relation;
            if (c.Show !== undefined && c.Show !== null)
              condition.Show = c.Show;
            if (c.Target !== undefined && c.Target !== null)
              condition.Target = c.Target;
            if (c.Value !== undefined && c.Value !== null)
              condition.Value = c.Value;
            group.conditions.push(condition);
          });
        q.conditionpipe.push(group);
      });
    return q;
  }
  public cloneAggregation(aggregation: Aggregation) {
    const q = new Aggregation();
    if (aggregation.name !== undefined && aggregation.name !== null)
      q.name = aggregation.name;
    if (aggregation.version !== undefined && aggregation.version !== null)
      q.version = aggregation.version;
    if (aggregation.expression !== undefined && aggregation.expression !== null)
      q.expression = aggregation.expression;

    q.parameter = new QueryParameter();
    if (
      aggregation.parameter !== undefined &&
      aggregation.parameter.distinctMrid !== undefined &&
      aggregation.parameter.distinctMrid !== null
    )
      q.parameter.distinctMrid = aggregation.parameter.distinctMrid;
    if (
      aggregation.parameter !== undefined &&
      aggregation.parameter.isMridMode !== undefined &&
      aggregation.parameter.isMridMode !== null
    )
      q.parameter.isMridMode = aggregation.parameter.isMridMode;
    if (
      aggregation.parameter !== undefined &&
      aggregation.parameter.limit !== undefined &&
      aggregation.parameter.limit !== null
    )
      q.parameter.limit = aggregation.parameter.limit;
    if (
      aggregation.parameter !== undefined &&
      aggregation.parameter.sequence !== undefined &&
      aggregation.parameter.sequence !== null
    )
      q.parameter.sequence = aggregation.parameter.sequence;
    if (
      aggregation.parameter !== undefined &&
      aggregation.parameter.strict !== undefined &&
      aggregation.parameter.strict !== null
    )
      q.parameter.strict = aggregation.parameter.strict;
    if (
      aggregation.conditionpipe !== undefined &&
      aggregation.conditionpipe !== null
    )
      aggregation.conditionpipe.forEach((p) => {
        const group = new ConditionGroup();
        if (p.name !== undefined && p.name !== null) group.name = p.name;
        if (p.relation !== undefined && p.relation !== null)
          group.relation = p.relation;
        if (p.conditions !== undefined && p.conditions !== null)
          p.conditions.forEach((c) => {
            const condition = new Condition();
            if (c.AddtionalValue !== undefined && c.AddtionalValue !== null)
              condition.AddtionalValue = c.AddtionalValue;
            if (c.DataType !== undefined && c.DataType !== null)
              condition.DataType = c.DataType;
            if (c.Db !== undefined && c.Db !== null) condition.Db = c.Db;
            if (c.DicColumns !== undefined && c.DicColumns !== null)
              condition.DicColumns = c.DicColumns;
            if (c.DicTable !== undefined && c.DicTable !== null)
              condition.DicTable = c.DicTable;
            if (c.IsShow !== undefined && c.IsShow !== null)
              condition.IsShow = c.IsShow;
            if (c.Operation !== undefined && c.Operation !== null)
              condition.Operation = c.Operation;
            if (c.Public !== undefined && c.Public !== null)
              condition.Public = c.Public;
            if (c.Relation !== undefined && c.Relation !== null)
              condition.Relation = c.Relation;
            if (c.Show !== undefined && c.Show !== null)
              condition.Show = c.Show;
            if (c.Target !== undefined && c.Target !== null)
              condition.Target = c.Target;
            if (c.Value !== undefined && c.Value !== null)
              condition.Value = c.Value;
            group.conditions.push(condition);
          });
        q.conditionpipe.push(group);
      });
    if (aggregation.statistics !== undefined && aggregation.statistics !== null)
      aggregation.statistics.forEach((s) => {
        const statistic = new Statistic();
        q.statistics.push(statistic);
        if (s.terms !== undefined && s.terms !== null) {
          s.terms.forEach((t) => {
            const st = new StatisticTerm();
            if (t.datatype !== undefined && t.datatype !== null)
              st.datatype = t.datatype;
            if (t.name !== undefined && t.name !== null) st.name = t.name;
            if (t.parameter !== undefined && t.parameter !== null)
              st.parameter = t.parameter;
            if (t.show !== undefined && t.show !== null) st.show = t.show;
            if (t.statistictype !== undefined && t.statistictype !== null)
              st.statistictype = t.statistictype;
            if (t.target !== undefined && t.target !== null)
              st.target = t.target;
            statistic.terms.push(st);
          });
        }
        if (s.conditions !== undefined && s.conditions !== null) {
          s.conditions.forEach((c) => {
            const condition = new Condition();
            if (c.AddtionalValue !== undefined && c.AddtionalValue !== null)
              condition.AddtionalValue = c.AddtionalValue;
            if (c.DataType !== undefined && c.DataType !== null)
              condition.DataType = c.DataType;
            if (c.Db !== undefined && c.Db !== null) condition.Db = c.Db;
            if (c.DicColumns !== undefined && c.DicColumns !== null)
              condition.DicColumns = c.DicColumns;
            if (c.DicTable !== undefined && c.DicTable !== null)
              condition.DicTable = c.DicTable;
            if (c.IsShow !== undefined && c.IsShow !== null)
              condition.IsShow = c.IsShow;
            if (c.Operation !== undefined && c.Operation !== null)
              condition.Operation = c.Operation;
            if (c.Public !== undefined && c.Public !== null)
              condition.Public = c.Public;
            if (c.Relation !== undefined && c.Relation !== null)
              condition.Relation = c.Relation;
            if (c.Show !== undefined && c.Show !== null)
              condition.Show = c.Show;
            if (c.Target !== undefined && c.Target !== null)
              condition.Target = c.Target;
            if (c.Value !== undefined && c.Value !== null)
              condition.Value = c.Value;
            statistic.conditions.push(condition);
          });
        }
        if (s.caculateterms !== undefined && s.caculateterms !== null) {
          s.caculateterms.forEach((t) => {
            const st = new CalculateTerm();
            if (t.form !== undefined && t.form !== null) st.form = t.form;
            if (t.name !== undefined && t.name !== null) st.name = t.name;
            if (t.parameter !== undefined && t.parameter !== null)
              st.parameter = t.parameter;

            statistic.caculateterms.push(st);
          });
        }
      });

    return q;
  }
  public validOperation(type: string, optype: string): boolean {
    let t = 'str';
    if (type === 'num') t = 'num';
    if (type === 'date') t = 'date';
    return this.store.validOperation[t].includes(optype);
  }
  public async setModel(item: QueryPackage) {
    if (!this.isLogined()) {
      alert('没有操作权限，请联系管理员');
      return;
    }
    item.result = []; //always clear result
    let para = {};
    item['owner'] = this.store.loginUser.UserName;
    para['model'] = JSON.stringify(item);
    para['userid'] = this.store.loginUser.UserName;
    let furl = 'model/create';
    await this.postApi(para, furl);
    console.log('finish set ');
  }
  public async deleteModel(item: QueryPackage) {
    if (!this.isLogined()) {
      alert('没有操作权限，请联系管理员');
      return;
    }
    item.result = []; //always clear result
    let para = {};
    item['owner'] = this.store.loginUser.UserName;
    para['model'] = JSON.stringify(item);
    para['userid'] = this.store.loginUser.UserName;
    let furl = 'model/delete';
    await this.postApi(para, furl);
    console.log('finish delete ');
  }

  getMonth(d) {
    let m = d.getMonth() + 1;
    if (m < 10) return '0' + m;
    return m;
  }
  getDay(d) {
    let m = d.getDate();
    if (m < 10) return '0' + m;
    return m;
  }
  public getlocalTime(datetime) {
    let r = new Date(Date.parse(datetime));

    let s = r.getFullYear() + '-' + this.getMonth(r) + '-' + this.getDay(r);

    return s;
    // 处理成为时间戳
    let timestamp = new Date(Date.parse(datetime));
    // timestamp = timestamp.getTime();
    // timestamp = timestamp / 1000;

    // // 增加8个小时，北京时间比utc时间多八个时区
    // var timestamp = timestamp + 8 * 60 * 60;

    // 时间戳转为时间

    //return beijing_datetime;
  }
  public selectitem = (selectedList: string[]) => {
    let currentlist: Condition[] = [];
    selectedList.forEach((v) => {
      let c = new Condition();
      c.Target = v;

      c.Show = this.getShow(v);

      let item = this.getInfo(c.Show);
      //if (item.datatype === "num") c.Value = "0";
      // if (item.datatype === "date") {
      //   c.Value = String(new Date(1700, 1, 1));
      //   c.AddtionalValue = String(new Date(1700, 1, 1));
      // }
      c.DicTable = item.dictable;
      c.DicColumns = item.dicColumn;
      c.Db = item.db;
      c.DataType = item.datatype;
      c.Options = item.options;

      currentlist.push(c);
    });
    return currentlist;
  };
  public getShow = (v: string) => {
    let s = this.store.AllergyConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.BaseConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.ClinicConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.CommonConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.DoctorConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.FeeConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.InPatientConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.OperateConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.OthersConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.SurgeryConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.TransConditionList.find((x) => x.name == v);
    if (s != undefined) return s.show;
    s = this.store.ContactCondition.find((x) => x.name == v);
    if (s != undefined) return s.show;
    return '';
  };
  public getInfo = (v: string): queryCondition => {
    let s = this.store.AllergyConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.BaseConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.ClinicConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.CommonConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.DoctorConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.FeeConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.InPatientConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.OperateConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.OthersConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.SurgeryConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.TransConditionList.find((x) => x.show == v);
    if (s != undefined) return s;
    s = this.store.ContactCondition.find((x) => x.show == v);
    if (s != undefined) return s;
    return undefined;
  };
  public getInfoByTarget = (v: string): queryCondition => {
    let s = this.store.AllergyConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.BaseConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.ClinicConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.CommonConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.DoctorConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.FeeConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.InPatientConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.OperateConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.OthersConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.SurgeryConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.TransConditionList.find((x) => x.name == v);
    if (s != undefined) return s;
    s = this.store.ContactCondition.find((x) => x.name == v);
    if (s != undefined) return s;
    return undefined;
  };
  clearitem = (list: queryCondition[]) => {
    list.forEach((v) => {
      v.selected = false;
    });
  };
  public clearSelection() {
    this.clearitem(this.store.AllergyConditionList);
    this.clearitem(this.store.BaseConditionList);
    this.clearitem(this.store.ClinicConditionList);
    this.clearitem(this.store.CommonConditionList);
    this.clearitem(this.store.ContactCondition);
    this.clearitem(this.store.DoctorConditionList);
    this.clearitem(this.store.FeeConditionList);
    this.clearitem(this.store.InPatientConditionList);
    this.clearitem(this.store.OperateConditionList);
    this.clearitem(this.store.SurgeryConditionList);
    this.clearitem(this.store.TransConditionList);
    this.clearitem(this.store.OthersConditionList);
  }
  rstr = new RegExp(',', 'g');
  codeSingleQuote = '，';
  getCsv(data, mapProperties) {
    if (data === undefined || data.length === 0) return '';
    let element = data[0];
    if (mapProperties === undefined) {
      mapProperties = Object.keys(element);
    }
    //let mapProperties = Object.keys(element);
    let s = mapProperties.join(',');
    s += '\n';
    console.log(s);
    for (let i = 0; i < data.length; i++) {
      const v = data[i];
      let ds = [];
      for (let key of mapProperties) {
        if (v[key] === undefined || v[key] === null) ds.push('');
        else {
          ds.push(v[key].toString().replace(this.rstr, this.codeSingleQuote));
        }
      }
      s += ds.join(',') + '\n';
    }

    //console.log(s);
    return s;
  }
  getsort() {
    return {};
  }
  // public async getConditionInfo(condition: Condition) {
  //   if (condition === undefined) return undefined;
  //   let r = await this.getDic(condition);
  //   console.log(r);
  //   return r;
  // }
  public async getDic(condition: Condition) {
    let para = {};
    para['dictable'] = condition.DicTable;
    para['diccolumns'] = condition.DicColumns;
    para['db'] = condition.Db;
    const url = this.store.conf.apiUrl + 'dic';
    var furl = url + '?';
    console.log(furl);
    para['operatorID'] = this.store.loginUser.UserName;

    for (const key of Object.keys(para)) {
      if (para.hasOwnProperty(key)) {
        furl = furl + key + '=' + para[key] + '&';
      }
    }
    const header = {
      'Content-Type': 'application/json',
    };

    return await this.httpService
      .get(furl, {
        headers: header,
        responseType: 'json',
      })
      .toPromise()
      .then(
        (data) => {
          console.log('data:');
          console.log(data);

          console.log('data body:');
          console.log(data['body']);
          return data['body'];
        },
        (error) => {
          console.log(error);
        }
      );
  }
  public CompatibilityQuery(q: Query) {
    q.conditionpipe.forEach((cg) => {
      cg.conditions.forEach((c) => {
        if (c['IsShow'] === undefined) c.IsShow = true;
      });
    });
    if (q.parameter.limit === undefined) {
      q.parameter.limit = {
        Diagnosis: 0,
        VAllergyDiagnosis: 0,
        VClinicDiagnosis: 0,
        VOperate: 0,
        VSurgery: 0,
        VTransfer: 0,
        VContact: 0,
        VICU: 0,
      };
    }
  }
  public async search(
    router: string,
    query: Query,
    filterconditions: Condition[],
    page: number,
    size: number,
    showIndicator = true
  ) {
    if (!this.isLogined()) {
      alert('没有操作权限，请联系管理员');
      return;
    }
    let tquery = JSON.parse(JSON.stringify(query)) as Query; //clone query
    tquery.showColumn = [];
    if (!this.store.queryAllColumnShow) {
      tquery.conditionpipe.forEach((v) => {
        v.conditions.forEach((c) => {
          if (
            tquery.showColumn.findIndex((s) => s === c.Target) == -1 &&
            c.IsShow
          ) {
            tquery.showColumn.push(c.Target);
          }
          this.filterDateValue(c);
          // if (c.Operation === "between")
          //   c.Value = c.Value + "," + c.AddtionalValue;
        });
      });
    }
    let para = {};
    para['query'] = JSON.stringify(tquery);
    para['filters'] = JSON.stringify(filterconditions);
    para['from'] = (page - 1) * size;
    para['size'] = size;

    para['sort'] = JSON.stringify(this.getsort());

    var url: string = '';
    if (!router.endsWith('/')) {
      url = router + '/' + 'search';
    } else {
      url = router + 'search';
    }

    let r = await this.postApi(para, url, showIndicator);

    return r;
  }

  public async aggregate(
    //just a query aggregate request
    router: string,
    aggregattion: Aggregation,
    returnResult = false,
    showIndicator = true
  ) {
    if (!this.isLogined()) {
      alert('没有操作权限，请联系管理员');
      return;
    }
    let taggregation = JSON.parse(JSON.stringify(aggregattion)) as Aggregation;
    taggregation.conditionpipe.forEach((cp) => {
      cp.conditions.forEach((c) => {
        this.filterDateValue(c);
      });
    });
    taggregation.statistics.forEach((cp) => {
      cp.conditions.forEach((c) => {
        this.filterDateValue(c);
      });
    });
    let para = {};
    para['aggregattion'] = JSON.stringify(taggregation);

    var url: string = '';
    console.log(router);
    if (!router.endsWith('/')) {
      url = router + '/' + 'aggregate';
    } else {
      url = router + 'aggregate';
    }

    let rs = await this.postApi(para, url, showIndicator);
    let ro = JSON.parse(rs as string);
    if (returnResult) return ro.body;
    this.store.aggregationresult = ro.body;
    //console.log('return:' + r);
  }
  private filterDateValue(c: Condition) {
    if (c.DataType === 'date') {
      if (c.Value !== undefined && c.Value !== '')
        c.Value = this.getlocalTime(c.Value);
      if (c.AddtionalValue !== undefined && c.AddtionalValue !== '')
        c.AddtionalValue = this.getlocalTime(c.AddtionalValue);
      //let dateCalcRes = c.Value; //? new Date(c.Value) : new Date(1700, 1, 1);
      //let adddateCalcRes = c.AddtionalValue;
      // ? new Date(c.AddtionalValue)
      // : new Date(1700, 1, 1);
      // if (dateCalcRes < new Date(1800, 1, 1)) c.Value = "";
      // else c.Value = dateCalcRes.toISOString();
      // if (adddateCalcRes < new Date(1800, 1, 1)) c.AddtionalValue = "";
      // else c.AddtionalValue = adddateCalcRes.toISOString();
    }
  }

  public async queryMrid(
    router: string,
    mrid: string,
    page: number,
    size: number
  ) {
    if (!this.isLogined()) {
      alert('没有操作权限，请联系管理员');
      return;
    }
    let con = new Condition();
    con.Target = 'MRID';
    con.Relation = 'And';
    con.Operation = 'Eq';
    con.Value = mrid;
    //this.store.doc.conditions = [con];
    let para = {};
    para['conditions'] = JSON.stringify([con]);
    para['from'] = (page - 1) * size;
    para['size'] = size;
    return await this.getApi(para, router);
    //console.log('return:' + r);
  }
  public async query(
    router: string,
    queryString: string,
    page: number,
    size: number,
    showIndicator = true
  ) {
    if (!this.isLogined()) {
      alert('没有操作权限，请联系管理员');
      return;
    }
    let con = new Condition();
    con.Relation = 'And';
    con.Operation = 'Eq';
    con.Value = queryString;
    //this.store.doc.conditions = [con];
    let para = {};
    para['conditions'] = JSON.stringify([con]);
    para['from'] = (page - 1) * size;
    para['size'] = size;
    return await this.getApi(para, router, showIndicator);
    //console.log('return:' + r);
  }
  public async addClick(index, docid) {
    let url = '';
    if (!index.endsWith('/')) {
      url = index + '/' + 'addCount';
    } else {
      url = index + 'addCount';
    }
    let para = {};
    para['id'] = docid;
    return await this.postApi(para, url);
  }
  public async getClick(index, docid) {
    let url = '';
    if (!index.endsWith('/')) {
      url = index + '/' + 'getCount';
    } else {
      url = index + 'getCount';
    }
    let para = {};
    para['id'] = docid;
    let r = await this.getApi(para, url);
    return r;
  }

  public async postApi(params: object, api: string, showIndicator = true) {
    if (showIndicator) this.store.busyIndicatorVisible = true;
    const url = this.store.conf.apiUrl + api;

    params['operatorID'] = this.store.loginUser.UserName;

    const header = {
      'Content-Type': 'application/json',
    };
    let request = this.httpService.post(url, params, {
      headers: header,
      responseType: 'text',
    });

    return await request.toPromise().then(
      (data) => {
        if (showIndicator) this.store.busyIndicatorVisible = false;
        return data;
      },
      (error) => {
        if (showIndicator) this.store.busyIndicatorVisible = false;
        console.log(error);
      }
    );
  }
  public putApi(params: object, api: string, showIndicator = true): any {
    if (showIndicator) this.store.busyIndicatorVisible = true;
    const url = this.store.conf.apiUrl + api;
    params['operatorID'] = this.store.loginUser.UserName;

    //params['operatorID'] = 'test';

    const header = {
      'Content-Type': 'application/json',
    };
    this.httpService
      .put(url, params, { headers: header, responseType: 'text' })
      .toPromise()
      .then(
        (data) => {
          if (showIndicator) this.store.busyIndicatorVisible = false;
          return data;
        },
        (error) => {
          if (showIndicator) this.store.busyIndicatorVisible = false;
          console.log(error);
        }
      );
  }
  public async getApi(params: object, api: string, showIndicator = true) {
    if (showIndicator) this.store.busyIndicatorVisible = true;
    const url = this.store.conf.apiUrl + api;
    var furl = url + '?';
    console.log(furl);
    params['operatorID'] = this.store.loginUser.UserName;
    //params['operatorID'] = 'test';
    for (const key of Object.keys(params)) {
      if (params.hasOwnProperty(key)) {
        furl = furl + key + '=' + params[key] + '&';
      }
    }
    const header = {
      'Content-Type': 'application/json',
    };
    return await this.httpService
      .get(furl, {
        headers: header,
        responseType: 'text',
      })
      .toPromise()
      .then(
        (data) => {
          if (showIndicator) this.store.busyIndicatorVisible = false;
          return data;
        },
        (error) => {
          if (showIndicator) this.store.busyIndicatorVisible = false;
          console.log(error);
          return JSON.stringify(error);
        }
      );
  }
}
